package org.example.service;

import org.example.model.BetRecord;
import org.example.model.Session;
import org.example.storage.BettingStorage;
import org.example.storage.SessionStorage;

import java.util.Optional;

public class BettingService {
    private final BettingStorage bettingStorage;
    private final SessionStorage sessionStorage;

    public BettingService(SessionStorage sessionStorage,BettingStorage bettingStorage) {
        this.sessionStorage = sessionStorage;
        this.bettingStorage = bettingStorage;
    }

    /**
     * 处理投注请求
     * @return true if successful, false if session is invalid
     */
    public boolean placeStake(int betOfferId, String sessionKey, int stake) {
        // 验证会话
        if (!isValidSession(sessionKey)) {
            return false;
        }

        // 获取客户ID
        Integer customerId = getCustomerIdFromSession(sessionKey);
        if (customerId == null) {
            return false;
        }

        // 创建并存储投注记录
        BetRecord betRecord = new BetRecord(betOfferId,customerId, stake);
        bettingStorage.addBet(betRecord);

        return true;
    }

    /**
     * 获取某个盘口的高投注列表
     */
    public String getHighStakes(int betOfferId) {
        return bettingStorage.getHighStakesForOffer(betOfferId);
    }

    private boolean isValidSession(String sessionKey) {
        return sessionStorage.findSessionByKey(sessionKey) != null;
    }

    private Integer getCustomerIdFromSession(String sessionKey) {
        Optional<Session> session = sessionStorage.findSessionByKey(sessionKey);
        return session.isPresent() ? session.get().getCustomerId() : null;
    }
}